package com.akbar.handler;

import com.akbar.utils.ResultUtil;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 注解@Valid 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultUtil<String> handleValidationException(MethodArgumentNotValidException e) {
        String errorMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(errorMessage);
        return ResultUtil.error(errorMessage);
    }


    /**
     *jwt异常
     */
    @ExceptionHandler(JwtException.class)
    public ResultUtil<String> handleJwtException(JwtException e) {
        String errorMessage = e.getMessage();
        log.error(errorMessage);
        return ResultUtil.error(errorMessage);
    }


    /**
     *最后捕获所有异常的父类
     */
    @ExceptionHandler(Exception.class)
    public ResultUtil<String> handleException(Exception e) {
        log.error(e.getMessage());
        return ResultUtil.error(e.getMessage());
    }
}
